import Vue from 'vue'
import _ from 'lodash'
export default {
	state: {
		user: null,
		authData: null // 新增字段保存完整响应数据
	},
	mutations: {
		 setUserData(state, payload) {
		      state.userData = payload
		    },
		login(state, payload) {
			state.user = user
			const { userData, authData } = payload
			state.user = {
        ...userData,
        uid: authData.uid,          // 将关键字段合并到user对象
        token: authData.newToken.token
      }
			state.authData = authData
			
			// 缓存用户信息
			Vue.prototype.$cache.set('_userInfo', user, 0)
			Vue.prototype.$cache.set('_authData', authData, 0)
		},
		logout(state) {
			state.user = null
			state.authData = null
			// 清理缓存用户信息
			Vue.prototype.$cache.delete('_userInfo')
			Vue.prototype.$cache.delete('_authData')
			
		}
	},
	actions: {
		async fetchUserData({ commit, state }) {
		      try {
		        // 1. 先检查Vuex中是否有数据（避免重复请求）
		        if (state.token && state.user) {
		          return { user: state.user, token: state.token }
		        }
		
		        // 2. 尝试从本地存储读取
		        const localUser = uni.getStorageSync('uni_id_user')
		        const localToken = uni.getStorageSync('uni_id_token')
		        
		        if (localToken && localUser) {
		          commit('SET_USER', localUser)
		          commit('SET_TOKEN', localToken)
		          return { user: localUser, token: localToken }
		        }
		
		        // 3. 从uni-id-co接口获取最新数据
		       /* const res = await uniCloud.callFunction({
		          name: 'uni-id-co',
		          data: { action: 'getUserInfo' }
		        }) */
		
		        /* if (res.result.errCode === 0) {
		          // 保存到Vuex和本地存储
		          commit('SET_USER', res.result.userInfo)
		          commit('SET_TOKEN', res.result.token)
		          uni.setStorageSync('uni_id_user', res.result.userInfo)
		          uni.setStorageSync('uni_id_token', res.result.token)
				  console.log('user.js fetchUserData',res.result);
		          return res.result
		        } else {
		          throw new Error(res.result.errMsg || '获取用户信息失败')
		        } */
		      } catch (e) {
		        // 清除无效数据
		        commit('CLEAR_USER')
		        uni.removeStorageSync('uni_id_user')
		        uni.removeStorageSync('uni_id_token')
		        throw e
		      }
		    },
		saveUserData({ commit }, data) {
		      commit('setUserData', data)
		    },
		autoLogin({ commit, getters, dispatch }) {
			// uni.reLaunch({
			// 	url: '/pages/index/index'
			// })
			// 判断本地是否有账号信息，如果有，就自动重新登录
			if (getters.user && getters.user.id && getters.user.name && getters.user.passwd) {
				const params = {
					name: getters.user.name,
					passwd: getters.user.passwd
				}
				uni.showLoading({
					title: '自动登录中...'
				})
				dispatch('login', params).then(res => {
					uni.hideLoading()
					// uni.showToast({
					// 	title: '已自动登录！',
					// 	icon: 'success'
					// })
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/index/index'
						})
					}, 1000)
				}).catch(() => {
					uni.hideLoading()
					uni.showToast({
						title: '会话过期，请重新登录！',
						icon: 'none'
					})
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/login/login'
						})
					}, 1000)
				})
			} else {
				// 如果本地没有账号信息，就提示用户必须登录
				uni.showModal({
					title: '未登录',
					content: '您未登录，需要登录后才能继续',
					showCancel: false,
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							uni.reLaunch({
								url: '/pages/login/login'
							})
						}
					}
				})
			}
		},
		async login({ commit }, params) {
		      try {
		        const res = await Vue.prototype.$minApi.login(params)
		        
		        if (res.ok()) {
		          // 构造payload
		          const payload = {
		            userData: { ...params, ...res.data }, // 原用户数据
		            authData: {                          // 微信登录返回的结构
		              ...res.data.result,                // 你的result数据
		              loginType: 'weixin'                // 确保类型标识
		            }
		          }
		          
		          commit('login', payload)
		          return Promise.resolve(res)
		        } else {
		          return Promise.reject(res)
		        }
		      } catch (err) {
		        return Promise.reject(err)
		      }
		    },
		login_tmp({ commit }, params) {
			return new Promise((resolve, reject) => {
				Vue.prototype.$minApi.login().then(res => {
					if (res.ok()) {
						let tmp = { ...params, ...res.data }
						commit('login', tmp)

						// 关于消息推送的保存
						// 保存clientid到服务器
						// #ifdef APP-PLUS
						const clientInfo = plus.push.getClientInfo()
						let pushUser = {
							clientid: clientInfo.clientid,
							appid: clientInfo.appid,
							appkey: clientInfo.appkey,
							userName: tmp.userName,
							userRole: tmp.roleStr
						}
						// 提交api请求，服务端保存客户端角色信息
						// Vue.prototype.$minApi.savePushUser(pushUser)
						// #endif

						resolve(res)
					} else {
						reject(res)
					}
				}).catch(err => {
					reject(err)
				})
			})
		},
		logout({ commit }) {
			commit('logout')
			uni.reLaunch({
				url: '/pages/login/login'
			})
		}
	},
	getters: {
		isLoggedIn: state => !!state.token,
		   getUserData: state => state.userData||{},
		
		user: state => {
			if (state.user) {
				//return state.user
				return state.user || Vue.prototype.$cache.get('_userInfo')
			}
			//return Vue.prototype.$cache.get('_userInfo')
			authData: state => {
			      return state.authData || Vue.prototype.$cache.get('_authData')
			    }				
		}
	}
}
